﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Autofac;
using FluentValidation;
using NHibernate;
using RevClinic.Core.Resources;
using RevClinic.Core.Commands;

namespace RevClinic.Core
{
    public class CommandInvoker : ICommandInvoker
    {
        private ISessionFactory _sessionFactory = null;
        private IHandlerProvider _handlerProvider = null;

        public CommandInvoker(ISessionFactory factory, IHandlerProvider handlers)
        {
            _sessionFactory = factory;
            _handlerProvider = handlers;
        }

        public void Execute<TCommand>(TCommand command) where TCommand : ICommand
        {
            //resolve current session
            ISession currentSession = _sessionFactory.GetCurrentSession();

            //resolve all executable command handlers
            ICommandHandler<TCommand> handler = _handlerProvider.HandlerFor<TCommand>();

            //run handler in transaction and
            //if exception occure, rollback and rethrow it
            using (ITransaction transaction = currentSession.BeginTransaction()) {
                try {
                    handler.Handle(command);
                    transaction.Commit();
                } catch (Exception ex) {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }
    }
}
